package entity;

import javax.swing.text.MaskFormatter;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author Zzy
 * @date Crated in 2018-08-29 14:09
 */
public class BplusTree implements B {
    /**
     * 根节点
     */
    protected Node root;

    /**
     * 阶数，M值
     */
    protected int order;

    /**
     * 叶子节点的链表头
     */
    protected Node head;

    public Node getHead() {
        return head;
    }

    public void setHead(Node head) {
        this.head = head;
    }

    public Node getRoot() {
        return root;
    }

    public void setRoot(Node root) {
        this.root = root;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    @Override
    public Object get(Comparable key) {
        return root.get(key);
    }

    @Override
    public void remove(Comparable key) {
        root.remove(key, this);

    }

    @Override
    public void insertOrUpdate(Comparable key, Object obj) {
        root.insertOrUpdate(key, obj, this);

    }

    public BplusTree(int order) {
        if (order < 3) {
            System.out.print("order must be greater than 2");
            System.exit(0);
        }
        this.order = order;
        root = new Node(true, true);
        head = root;
    }

    public void print(Node node) {
        List<Node> children = node.getChildren();
        if (children == null) {
            System.out.println(node.toString());
        } else {
            for (Node cnode : children) {
                print(cnode);
            }
        }
    }

    //测试
    public static void main(String[] args) {
        int a=Integer.parseInt(args[0]);
        long start=new Date().getTime();
        System.out.println(start);
        BplusTree tree = new BplusTree(3000);
        for (int i = 0; i < a; i++) {
            int num = new Random().nextInt(Integer.MAX_VALUE);
            tree.insertOrUpdate(num, num);
//            if (i%10000==0){
//                System.out.println(i);
//            }
        }
//        tree.print(tree.root);
        long end=new Date().getTime();
        System.out.println(end);
        System.out.println(end-start);
        /*BplusTree tree = new BplusTree(4);
        Random random = new Random();
        long current = System.currentTimeMillis();
        for (int j = 0; j < 100000; j++) {
            for (int i = 0; i < 100; i++) {
                int randomNumber = random.nextInt(1000);
                tree.insertOrUpdate(randomNumber, randomNumber);
            }

            for (int i = 0; i < 100; i++) {
                int randomNumber = random.nextInt(1000);
                tree.remove(randomNumber);
            }
        }

        long duration = System.currentTimeMillis() - current;
        System.out.println("time elpsed for duration: " + duration);
        int search = 80;
        System.out.print(tree.get(search));*/
    }

}
